package myJs.projectCps.enrichNetworkPlot

import myJs.myPkg.yup.Yup
import myJs.tool.Tool._
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._

import scala.collection.mutable
import scala.concurrent.Future
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.timers.SetTimeoutHandle

/** Created by yz on 9/11/2022
  */
object Schema {

  case class ValidInfo(v: String, valid: Boolean)

  val cacheMap = mutable.SeqMap[String, ValidInfo]()

  def cacheTest(key: String)(f: String => Future[Boolean]) = (v: String) => {
    val beforeV = cacheMap.getOrElse(key, ValidInfo("", true))
    if (beforeV.v != v) {
      f(v).map { x =>
        cacheMap.put(key, ValidInfo(v, x))
        x
      }.toJSPromise
    } else {
      Future {
        beforeV.valid
      }.toJSPromise
    }
  }

  def transformF = (v: Double) => {
    if (v.toString == "") {
      js.undefined
    } else js.defined(v)
  }

  var delayTimer = null: SetTimeoutHandle


  val schema = Yup
    .`object`()
    .shape(
      js.Dictionary(
        "width" -> Yup
          .number()
          .positive(messages("greaterThan", 0))
          .typeError(message = messages("numeric") ),
        "height" -> Yup
          .number()
          .positive(messages("greaterThan", 0))
          .typeError(message = messages("numeric")),
        "mainTitleFont" -> Yup
          .number()
          .positive(messages("greaterThan", 0))
          .typeError(message = messages("numeric")),
        "xTitleFont" -> Yup
          .number()
          .positive(messages("greaterThan", 0))
          .typeError(message = messages("numeric")),
        "xFont" -> Yup
          .number()
          .positive(messages("greaterThan", 0))
          .typeError(message = messages("numeric")),
        "yTitleFont" -> Yup
          .number()
          .positive(messages("greaterThan", 0))
          .typeError(message = messages("numeric")),
        "yFont" -> Yup
          .number()
          .positive(messages("greaterThan", 0))
          .typeError(message = messages("numeric")),
        "legendTitleFont" -> Yup
          .number()
          .positive(messages("greaterThan", 0))
          .typeError(message = messages("numeric")),
        "legendFont" -> Yup
          .number()
          .positive(messages("greaterThan", 0))
          .typeError(message = messages("numeric")),

      )
    )

}
